import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router'
import { PageTitle } from "./page-title"
import { AjaxService } from './ajax.service'
import { Project } from './project'
import { ProjectService } from "./project.service"
import { PlanService } from "./plan.service"
import { UserService } from "./user.service";
import { Type } from './type'
import { TypeService } from './type.service'
import { User } from "./user";
import { Plan } from "./plan";
import { Milestone } from "./milestone";

@Component({
  selector: 'projects',
  templateUrl: "./projects.component.html",
  styleUrls: [ "./projects.component.css" ]
})
export class ProjectsComponent implements OnInit {
  image_url: string
  plans: Array<Plan>
  projects: Array<Project>
  user: User
  mine: User
  types: Array<Type>
  users: Array<User>
  sideShowed: boolean
  projectShowed: boolean
  project: Project = new Project()
  plan: Plan = new Plan()
  back_plan: Plan = new Plan()
  milestone: Milestone = new Milestone()
  bh = AjaxService.APIROOT + '/plans'

  constructor(private userService: UserService,
              private projectService: ProjectService,
              private planService: PlanService,
              private typeService: TypeService,
              private pageTitle: PageTitle,
              private router: Router) { }

  ngOnInit(): void {
    this.pageTitle.back = null
    this.pageTitle.title = "项目排期表"
    this.userService.getUserMine().then(user => {
      if (!user) return false
      this.user = user
      console.log(user)
      /*if (user.manager || user.supervisor) */
      /*this.planService.getList()
        .then(plans => this.plans = plans)*/
        this.setplans()
    })
  }

  setplans() {
      this.planService.getList()
        .then(plans => this.plans = plans)
  }

 
  createProject(id): void {
    this.projectShowed = true
    this.project = new Project()
   /* this.milestones = new Array<Milestone>()*/
   this.project.milestones_attributes = []
   var milestone = new Milestone()
   this.project.milestones_attributes.push(milestone)
    this.project.plan_id = id
    this.typeService.getList().then(types => {
      this.types = types
      this.project.type_id = types[0].id
    })
    this.userService.getList().then(users => {
      this.users = users
      if (users[0])
        this.project.leader_id = users[0].id
      if (!this.project.demander_id) this.project.demander_id = ""
    })
  }

  createPlan(): void {
    if(this.user.manager) {
       this.sideShowed = true
       this.plan = new Plan()
    }
    else {
      alert('权限不足')
    }
  }

  delete(i): void {
    this.project.milestones_attributes.splice(i,1)
  }

  add(): void {
    var milestone = new Milestone()
   this.project.milestones_attributes.push(milestone)
  }

  updatePlan(id): void {
    this.sideShowed = true
    this.planService.get(id).then(plan => this.plan = plan)
  }
  
  save(plan): void {
      var token = localStorage.getItem("token")
      var formData =  new FormData();
      formData.append('token',token)
      formData.append('plan[name]', plan.name)
      formData.append('plan[image]', plan.image)
       if (plan.id) {
         formData.append('id', plan.id)
       }
       this.upload(formData).then()
         /*plan =>{
         this.plans = this.plans.filter(t_plan => {
           if(t_plan.id == plan.id){
             t_plan.name = plan.name
             t_plan.image = plan.image
           }
           return t_plan
         })
          this.setplans()
       })*/
       
       this.sideShowed = false 
   }


   changeMoonCover(e){
     var windowURL = window.URL 
     this.image_url = windowURL.createObjectURL(e.target.files[0]) 
     this.plan.image = e.target.files[0]
     console.log(this.plan.image)
   }

   goProject(project): void {
     if(this.user.manager) {
       this.router.navigate(["projects", project.id])
      }
      else {
       alert('权限不足')
      }
    }


  submit(): void {
    this.projectShowed = false
    console.log(this.project)
    this.projectService.update(this.project).then(res => {
      if (res.error) {
        if (res.error == "TOKEN-ERROR")
          return alert("无法处理，需要登录")
        return alert("出现错误，" + (res.msg || res.error))
      }
       this.setplans()
    })
  }

  export(): void {
    var token = localStorage.getItem("token")
    window.location.href = this.bh + '/list.xls?token='+ token 
  }


  upload(formData): Promise<Plan>{
       var plan: Plan
       var url = this.bh;
       let xhr: XMLHttpRequest = new XMLHttpRequest();
       xhr.open('POST', url, true);

       // enctype For Multipart Request
        xhr.setRequestHeader("enctype", "multipart/form-data");

        // IE bug fixes to clear cache
        xhr.setRequestHeader("Cache-Control", "no-cache");
        xhr.setRequestHeader("Cache-Control", "no-store");
        xhr.setRequestHeader("Pragma", "no-cache"); 
      
        return new Promise<Plan>(resolve => {
          xhr.send(formData)
          xhr.onreadystatechange = () => {
            if (xhr.readyState === XMLHttpRequest.DONE) {
              resolve(JSON.parse(xhr.responseText).data)
              this.setplans()
            }
          }
        })
   }
}